package org.example.camundaapp.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.history.HistoricActivityInstance;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.example.camundaapp.bpm.service.CamundaDeployer;
import org.example.camundaapp.dto.TaskDTO;
import org.example.camundaapp.service.ProcessService;
import org.example.camundaapp.utils.BpmnToImageConverter;
import org.example.camundaapp.utils.ProcessDiagramUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 流程控制模块
 * @className: ProcessController
 * @author: ZHRJ
 * @date: 2025-06-26 11:27
 * @Version: 1.0
 * @description:
 */
@RestController
@RequestMapping("/api/process")
@Slf4j
public class ProcessController {

    private ProcessService processService;

    @Autowired
    public ProcessController(ProcessService processService) {
        this.processService = processService;
    }

    /**
     *  启动流程实例
     *  POST /api/process/start?processDefinitionKey=Process_193yq04
     *  {
     *   "initiator": "user1",
     *   "managerList": ["manager1", "manager2", "manager3"],
     *   "headList": ["head1", "head2"]
     * }
     * @param processKey 流程定义key
     * @param variables 流程变量
     * @return 启动的流程实例
     */
    @PostMapping("/startProcessInstance/{processKey}")
    public ResponseEntity<String> startProcessInstance(
            @PathVariable String processKey,
            @RequestBody Map<String, Object> variables) {
        log.info("启动流程实例，流程定义key：{}，流程变量：{}", processKey, variables);
        ProcessInstance processInstance = processService.startProcessInstance(processKey, variables);
        return ResponseEntity.ok("启动流程实例成功，流程实例ID：" + processInstance.getId()   );
    }

    /**
     * 启动流程 （推荐）
     * @param requestBody 请求体，包含流程定义 key、业务 key、发起人以及流程变量
     *{
     *   "processDefinitionKey": "Process_19w1rrm", // 流程定义Key（BPMN中的process.id）
     *   "businessKey": "BUS2023070001", // 业务唯一标识（如订单号、申请号）
     *   "initiator": "zhangsan", // 流程发起人ID
     *   "variables": {
     *     "userOneList": ["lisi", "wangwu", "zhaoliu"], // 或签任务处理人列表
     *     "userTwoList": ["lisi", "wangwu", "zhaoliu", "sunqi"], // 比例签任务处理人列表
     *     "userThreeList": ["lisi", "wangwu", "zhaoliu", "qianba", "zhoujiu"] // 会签任务处理人列表
     *   }
     * }
     * @return 启动流程的结果信息
     */
    @PostMapping("/start")
    public ResponseEntity<String> startProcess(@RequestBody JSONObject requestBody) {
        String processDefinitionKey = requestBody.getString("processDefinitionKey");
        String businessKey = requestBody.getString("businessKey");
        String initiator = requestBody.getString("initiator");
        Map<String, Object> variables = requestBody.getObject("variables", Map.class);

        // 将发起人信息添加到流程变量中
        if (variables != null) {
            variables.put("initiator", initiator);
        }

        log.info("启动流程，流程定义 key：{}，业务 key：{}，发起人：{}，流程变量：{}",
                processDefinitionKey, businessKey, initiator, variables);

        ProcessInstance processInstance = processService.startProcessInstance(processDefinitionKey, businessKey, variables);
        return ResponseEntity.ok("流程启动成功，流程实例 ID：" + processInstance.getId());
    }

    /**
     * 挂起流程
     * @param processInstanceId 流程实例ID
     * @return
     */
    @PostMapping("/suspend")
    public ResponseEntity<String> suspendProcess(@RequestParam String processInstanceId) {
        processService.suspendProcessInstance(processInstanceId);
        return ResponseEntity.ok("流程已挂起");
    }

    /**
     * 激活流程
     * @param processInstanceId 流程实例ID
     * @return
     */
    @PostMapping("/activate")
    public ResponseEntity<String> activateProcess(@RequestParam String processInstanceId) {
        processService.activateProcessInstance(processInstanceId);
        return ResponseEntity.ok("流程已激活");
    }

    /**
     * 删除流程实例
     * @param instanceId 流程实例ID
     * @param reason 删除原因
     * @return
     */
    @DeleteMapping("/delete")
    public ResponseEntity<String> deleteProcess(
            @RequestParam String instanceId,
            @RequestParam(required = false) String reason
    ) {
        processService.deleteProcessInstance(instanceId, reason);
        return ResponseEntity.ok("流程已删除");
    }

    /**
     * 删除部署定义
     * @param deploymentId 部署id
     */
    @DeleteMapping("/deleteDeployment")
    public ResponseEntity<String> deleteDeployment(String deploymentId) {
        try{
            CamundaDeployer camundaDeployer = new CamundaDeployer();
            camundaDeployer.deleteDeployment(deploymentId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseEntity.ok("删除部署成功");
    }

    @GetMapping("/getProcessStatus")
    public ResponseEntity<String> getProcessStatus(@RequestParam String processInstanceId) {
        return ResponseEntity.ok(processService.getProcessStatus(processInstanceId));
    }
}
